from data_access.database import Session
from sqlalchemy.exc import SQLAlchemyError

from data_access.models.models import Job


class JobDAO:
    def __init__(self):
        self.session = Session()

    def add_job(self, dispatch_code, job_id, job_name, job_type, job_frequency, job_status, task_id, last_job_id=None, next_job_id=None, comment=None):
        new_job = Job(
            dispatch_code=dispatch_code,
            job_id=job_id,
            job_name=job_name,
            job_type=job_type,
            job_frequency=job_frequency,
            job_status=job_status,
            task_id=task_id,
            last_job_id=last_job_id,
            next_job_id=next_job_id,
            comment=comment
        )
        try:
            self.session.add(new_job)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def get_job_by_job_id(self, job_id):
        try:
            return self.session.query(Job).filter(Job.job_id == job_id).first()
        except SQLAlchemyError as e:
            return None
        finally:
            self.session.close()

    def update_job(self, job_id, **kwargs):
        try:
            self.session.query(Job).filter(Job.job_id == job_id).update(kwargs)
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()

    def delete_job(self, job_id):
        try:
            self.session.query(Job).filter(Job.job_id == job_id).delete()
            self.session.commit()
            return True
        except SQLAlchemyError as e:
            self.session.rollback()
            return False
        finally:
            self.session.close()
